package cn.huanba.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * 限流
 */
@Configuration
public class KeyResolverConfiguration {
    /**
     * 限流规则：根据地址
     *
     * @return
     */
    //@Bean
    public KeyResolver pathKeyResolver() {
        //jdk1.8
        return exchange -> Mono.just(exchange.getRequest().getPath().toString());
        /* 匿名内部类
        return  new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getPath().toString());
            }
        };*/
    }

    /**
     * 根据参数限流
     *
     * @return
     */
    //@Bean
    public KeyResolver parameterKeyResolver() {
        //jdk1.8
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("uid"));
    }

    /**
     * 根据IP限流
     *
     * @return
     */
    @Bean
    public KeyResolver ipKeyResolver() {
        //jdk1.8
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}
